/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package th.stripes.action;

import com.google.inject.Inject;
import com.oas.thit._this.profile.depositor.xsd.DepositorProfileResponseBody;
import com.oas.thit._this.xsd.THISBaseDataElementBody;
import com.oas.thit.xmlmessage.xsd.Header;
import java.util.Date;
import java.text.SimpleDateFormat;

import able.stripes.JSP;
import java.util.List;
import javax.servlet.http.HttpSession;
import javax.xml.bind.JAXBElement;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import org.apache.commons.lang.ArrayUtils;
import th.manager.ResponseManager;
import th.manager.AkaunManager;
import th.model.Pengguna;
import th.stripes.BaseActionBean;
import th.stripes.Configuration;
import th.stripes.webservice.WebServiceUtil;
import org.apache.log4j.Logger;
import th.dao.THISutilDAO;
import th.manager.SMSgatewayManager;
import th.manager.UserManager;
import th.model.Akaun;
import th.model.InfoAudit;
import th.model.KodKebenaranTransaksi;
import th.model.THISutil;

/**
 *
 * @author faizal.azlee
 */
@UrlBinding("/tac")
public class TrxAuthorizationCodeActionBean extends BaseActionBean{
    
    private Pengguna pengguna;
    private String noTel;
    private Date trxDate;

    @Inject
    private WebServiceUtil webUtil; 
    @Inject 
    private ResponseManager responseManager;    
    @Inject
    private AkaunManager akaunManager;
    @Inject
    private UserManager userManager;
    @Inject
    private SMSgatewayManager sMSgatewayManager;
    @Inject
    Configuration conf; 
    @Inject 
    private THISutilDAO tHISutilDAO;
    
    private static String SUCCESSFUL = "0000";    
    private static String SYSTEM_ERROR = "9999";   
    private static String PROFILE_ENQ_MSG_ID = "TPDPPROFWD01";
    private static String HEADER_ID_PROFILE_ENQUIRY = "THSDPQR";
    private static String HEADER_ID_FND_TFR= "THSTHT3";
    private static String HEADER_ID_UPD_PROFILE = "THSDPUP";
    private static String HEADER_ID_ADD_FAV_ACC = "THFAVADD";
    private static String HEADER_ID_EDIT_FAV_ACC = "THFAVEDIT"; // ADD 26/09/2014
    private static String HEADER_ID_EDIT_SECURITY = "THMNGSEC"; // added in 2/6/2015
    
    private static Logger LOG = Logger.getLogger(TrxAuthorizationCodeActionBean.class);
    
    //added in 2/6/2015
     public Resolution generateTacSecurity() {  
        pengguna = getContext().getCurrentUser();
        StringBuilder sb = new StringBuilder(" e-THiJARI: Manage Security Features TH");
        
        String result = GenerateTac(HEADER_ID_EDIT_SECURITY, sb.toString());
        //String result = GenerateTacTest(HEADER_ID_EDIT_SECURITY, sb.toString());
        String[] resultArr = new String[2];
        resultArr = result.split(",");
        if(resultArr[0].trim().equals("200")){            
            noTel = resultArr[1].substring(0, resultArr[1].length()-3).concat("xxx");            
            trxDate = new Date();
            return new JSP("/popup/deposit/tacmsg.jsp");
        }else{ 
            addSimpleError("Kod Kebenaran Transaksi tidak berjaya di hantar buat masa ini. Sila cuba semula");
            return new JSP("/popup/deposit/tacmsgfailed.jsp");            
        }        
    }
     
     /*
      * Test 
      */
      public String GenerateTacTest(String operasi, String text) {
        
        
        HttpSession ses = context.getRequest().getSession();
        InfoAudit ia = new InfoAudit();
        ia.setDimasukOleh(pengguna);
        ia.setTarikhMasuk(new Date());

        Integer pinNumber =  new Double(000001 + Math.random() * (999999-000001)).intValue();
        String pinNumberStr = pinNumber.toString();
        if(pinNumberStr.trim().length()<6)
            pinNumberStr = pinNumberStr+"0";
        KodKebenaranTransaksi kodKebenaranTransaksi = sMSgatewayManager.findKodKebenaranTransaksiBySessionId(ses.getId(), operasi, "Y");

        //for testing purposes-heardcode pin number to 123456
        //remove once move to production
        
            if(kodKebenaranTransaksi != null){
                kodKebenaranTransaksi.setSah("N");
                kodKebenaranTransaksi.setInfoAudit(ia);
                sMSgatewayManager.saveTAC(kodKebenaranTransaksi);
            }

            kodKebenaranTransaksi = new KodKebenaranTransaksi();
            kodKebenaranTransaksi.setIdSessi(ses.getId());
            kodKebenaranTransaksi.setSah("Y");
            kodKebenaranTransaksi.setKodKebenaranTransaksi(pinNumberStr);
            kodKebenaranTransaksi.setOperasi(operasi);
            kodKebenaranTransaksi.setInfoAudit(ia);
            sMSgatewayManager.saveTAC(kodKebenaranTransaksi);

            String responseCode = "";
            String responseTAC = "9999";
//            try { // Call Web Service Operation
//                com.oas.thit._this.services.THISServices service = new com.oas.thit._this.services.THISServices();
//                com.oas.thit._this.services.THISServicesPortType port = service.getTHISServicesHttpSoap11Endpoint();
//                // TODO initialize WS operation arguments here
//                com.oas.thit._this.xsd.THISRequest req = new com.oas.thit._this.xsd.THISRequest();
//                com.oas.thit._this.xsd.ObjectFactory objFactory = new com.oas.thit._this.xsd.ObjectFactory();
//
//                req.setHeader( webUtil.createHeader(PROFILE_ENQ_MSG_ID, HEADER_ID_PROFILE_ENQUIRY) );
//
//                THISBaseDataElementBody reqBody = objFactory.createTHISBaseDataElementBody();
//
//                reqBody.setTHAcct(objFactory.createTHISBaseDataElementBodyTHAcct(akaunManager.getNoAkaun(pengguna.getNoKp(), "Y")));
//                reqBody.setTHICNo(objFactory.createTHISBaseDataElementBodyTHICNo(pengguna.getNoKp()));
//
//                JAXBElement<THISBaseDataElementBody> jReqBody =  objFactory.createTHISRequestBody(reqBody);
//                req.setBody(jReqBody);
//
//                // TODO process result here
//                com.oas.thit._this.profile.depositor.xsd.DepositorProfileResponse result = port.depositorProfileQuery(req);
//                Header header = result.getHeader().getValue();
//                responseCode = header.getResponseCode().getValue();
//                if (responseCode.equals(SUCCESSFUL)) {
//                    DepositorProfileResponseBody resp = result.getBody().getValue();
//                    if ( resp != null ) {
//                        //call web service sMS GateWay
//                        if(resp.getTHPhoneMobile().getValue().trim()!=null && !resp.getTHPhoneMobile().getValue().trim().equals("")){
//                            String mPhone = resp.getTHPhoneMobile().getValue().trim();
//                            StringBuilder sb = new StringBuilder(text);                            
//                            sb.append(". TAC:"+pinNumberStr+". Tidak melakukan transaksi? Hubungi ");
//                            THISutil tHISutil = tHISutilDAO.findById("101");                            
//                            sb.append(tHISutil.getDeskripsi().toString());
//                            responseTAC = sMSgatewayManager.sendSMS(mPhone, sb.toString())+","+mPhone;
//                        }
//                    }
//                }
//
//            } catch (Exception ex) {
//                LOG.error(ex);
//                responseCode = SYSTEM_ERROR;
//                addSimpleError("" + responseManager.getResponseMessage(responseCode, PROFILE_ENQ_MSG_ID));  
//             }
            return responseTAC;
        }
      
     public Resolution generateAccFavAddTac() {  
        pengguna = getContext().getCurrentUser();
        StringBuilder sb = new StringBuilder(" e-THiJARI: Penambahan Favourite Account TH");
        String result = GenerateTac(HEADER_ID_ADD_FAV_ACC, sb.toString(), getContext().getRequest().getSession().getId());
        String[] resultArr = new String[2];
        resultArr = result.split(",");
        if(resultArr[0].trim().equals("200")){            
            noTel = resultArr[1].substring(0, resultArr[1].length()-3).concat("xxx");            
            trxDate = new Date();
            return new JSP("/popup/deposit/tacmsg.jsp");
        }else{ 
            addSimpleError("Kod Kebenaran Transaksi tidak berjaya di hantar buat masa ini. Sila cuba semula");
            return new JSP("/popup/deposit/tacmsgfailed.jsp");            
        }        
    }
     
    public Resolution generateAccFavUpdateTac() {  
        pengguna = getContext().getCurrentUser();
        StringBuilder sb = new StringBuilder(" e-THiJARI: Kemaskini Favourite Account TH");
        String result = GenerateTac(HEADER_ID_EDIT_FAV_ACC, sb.toString(), getContext().getRequest().getSession().getId());
        String[] resultArr = new String[2];
        resultArr = result.split(",");
        if(resultArr[0].trim().equals("200")){            
            noTel = resultArr[1].substring(0, resultArr[1].length()-3).concat("xxx");            
            trxDate = new Date();
            return new JSP("/popup/deposit/tacmsg.jsp");
        }else{ 
            addSimpleError("Kod Kebenaran Transaksi tidak berjaya di hantar buat masa ini. Sila cuba semula");
            return new JSP("/popup/deposit/tacmsgfailed.jsp");            
        }        
    }
     
    public Resolution generateFundTranferTac() {
        
        pengguna = getContext().getCurrentUser();
        
        String amount = getContext().getRequest().getParameter("amount");
        String noAkaun = getContext().getRequest().getParameter("noAkaun");
        String noKp = getContext().getRequest().getParameter("noKp");
        String akaunDari = getContext().getRequest().getParameter("akaunDari");
        String noKpDari = getContext().getRequest().getParameter("noKpDari");
        
        if (!checkAcc(noAkaun, noKp, akaunDari, noKpDari)) {
            return new JSP("/popup/deposit/tacmsgfailed.jsp");
        }
        
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        String dtStr = sdf.format(new Date());        
        
        StringBuilder sb = new StringBuilder(" e-THiJARI: Pindahan Simpanan RM");
        sb.append(amount);
        sb.append(" pada ");
        sb.append(dtStr);
        
        String result = GenerateTac(HEADER_ID_FND_TFR, sb.toString(), getContext().getRequest().getSession().getId());
        String[] resultArr = new String[2];
        resultArr = result.split(",");
        if(resultArr[0].trim().equals("200")){
            noTel = resultArr[1].substring(0, resultArr[1].length()-3).concat("xxx");            
            trxDate = new Date();
            return new JSP("/popup/deposit/tacmsg.jsp");
        }else{
            addSimpleError("Kod Kebenaran Transaksi tidak berjaya di hantar buat masa ini. Sila cuba semula");
            return new JSP("/popup/deposit/tacmsgfailed.jsp");
        }
        
    }
    
    public Resolution generateProfileUpdateTac() {  
        pengguna = getContext().getCurrentUser();
        StringBuilder sb = new StringBuilder(" e-THiJARI: Kemaskini profil TH");
        String result = GenerateTac(HEADER_ID_UPD_PROFILE, sb.toString(), getContext().getRequest().getSession().getId());
        String[] resultArr = new String[2];
        resultArr = result.split(",");
        if(resultArr[0].trim().equals("200")){            
            noTel = resultArr[1].substring(0, resultArr[1].length()-3).concat("xxx");            
            trxDate = new Date();
            return new JSP("/popup/deposit/tacmsg.jsp");
        }else{ 
            addSimpleError("Kod Kebenaran Transaksi tidak berjaya di hantar buat masa ini. Sila cuba semula");
            return new JSP("/popup/deposit/tacmsgfailed.jsp");            
        }        
    }
    
    public String GenerateTac(String operasi, String text, String sessionId) {
        
        
//        HttpSession ses = context.getRequest().getSession();
        InfoAudit ia = new InfoAudit();
        ia.setDimasukOleh(pengguna);
        ia.setTarikhMasuk(new Date());

        Integer pinNumber =  new Double(000001 + Math.random() * (999999-000001)).intValue();
        String pinNumberStr = pinNumber.toString();
        if(pinNumberStr.trim().length()<6)
            pinNumberStr = pinNumberStr+"0";
        KodKebenaranTransaksi kodKebenaranTransaksi = sMSgatewayManager.findKodKebenaranTransaksiBySessionId(sessionId, operasi, "Y");

        //for testing purposes-heardcode pin number to 123456
        //remove once move to production
        
            if(kodKebenaranTransaksi != null){
                kodKebenaranTransaksi.setSah("N");
                kodKebenaranTransaksi.setInfoAudit(ia);
                sMSgatewayManager.saveTAC(kodKebenaranTransaksi);
            }

            kodKebenaranTransaksi = new KodKebenaranTransaksi();
            kodKebenaranTransaksi.setIdSessi(sessionId);
            kodKebenaranTransaksi.setSah("Y");
            kodKebenaranTransaksi.setKodKebenaranTransaksi(pinNumberStr);
            kodKebenaranTransaksi.setOperasi(operasi);
            kodKebenaranTransaksi.setInfoAudit(ia);
            sMSgatewayManager.saveTAC(kodKebenaranTransaksi);

            String responseCode = "";
            String responseTAC = "9999";
            try { // Call Web Service Operation
                com.oas.thit._this.services.THISServices service = new com.oas.thit._this.services.THISServices();
                com.oas.thit._this.services.THISServicesPortType port = service.getTHISServicesHttpSoap11Endpoint();
                // TODO initialize WS operation arguments here
                com.oas.thit._this.xsd.THISRequest req = new com.oas.thit._this.xsd.THISRequest();
                com.oas.thit._this.xsd.ObjectFactory objFactory = new com.oas.thit._this.xsd.ObjectFactory();

                req.setHeader( webUtil.createHeader(PROFILE_ENQ_MSG_ID, HEADER_ID_PROFILE_ENQUIRY) );

                THISBaseDataElementBody reqBody = objFactory.createTHISBaseDataElementBody();

                reqBody.setTHAcct(objFactory.createTHISBaseDataElementBodyTHAcct(akaunManager.getNoAkaun(pengguna.getNoKp(), "Y")));
                reqBody.setTHICNo(objFactory.createTHISBaseDataElementBodyTHICNo(pengguna.getNoKp()));

                JAXBElement<THISBaseDataElementBody> jReqBody =  objFactory.createTHISRequestBody(reqBody);
                req.setBody(jReqBody);

                // TODO process result here
                com.oas.thit._this.profile.depositor.xsd.DepositorProfileResponse result = port.depositorProfileQuery(req);
                Header header = result.getHeader().getValue();
                responseCode = header.getResponseCode().getValue();
                if (responseCode.equals(SUCCESSFUL)) {
                    DepositorProfileResponseBody resp = result.getBody().getValue();
                    if ( resp != null ) {
                        //call web service sMS GateWay
                        if(resp.getTHPhoneMobile().getValue().trim()!=null && !resp.getTHPhoneMobile().getValue().trim().equals("")){
                            String mPhone = resp.getTHPhoneMobile().getValue().trim();
                            StringBuilder sb = new StringBuilder(text);                            
                            sb.append(". TAC:"+pinNumberStr+". Tidak melakukan transaksi? Hubungi ");
                            THISutil tHISutil = tHISutilDAO.findById("101");                            
                            sb.append(tHISutil.getDeskripsi().toString());
                            responseTAC = sMSgatewayManager.sendSMS(mPhone, sb.toString())+","+mPhone;
                        }
                    }
                }

            } catch (Exception ex) {
                LOG.error(ex);
                responseCode = SYSTEM_ERROR;
                addSimpleError("" + responseManager.getResponseMessage(responseCode, PROFILE_ENQ_MSG_ID));  
             }
            return responseTAC;
        }

    public String getNoTel() {
        return noTel;
    }

    public void setNoTel(String noTel) {
        this.noTel = noTel;
    }

    public Date getTrxDate() {
        return trxDate;
    }

    public void setTrxDate(Date trxDate) {
        this.trxDate = trxDate;
    }
    
    private boolean checkAcc(String noAcc1,String noKp1, String noAcc2, String noKp2) {
        List<Akaun> akauns = pengguna.getSenaraiAkaun();
        
        String[] noAcc = new String[akauns.size()];
        
        String[] noKp = new String[akauns.size()]; 
        
        boolean isValidAcc = false;
        
        boolean isValidKp = false;
        
        int i = 0;
        
        for (Akaun akaun : akauns) {
            noAcc[i] = akaun.getAkaunTmbhn();          
            noKp[i] = akaun.getNoPengenalanTmbhn();
            i++;
        }
        
        if (ArrayUtils.contains(noAcc, noAcc1)){
            isValidAcc = ArrayUtils.contains(noAcc, noAcc2);
        }
        
        if (ArrayUtils.contains(noKp, noKp1)){
            isValidKp = ArrayUtils.contains(noKp, noKp2);
        }
        
        return (isValidAcc && isValidKp);        
    }

     public Pengguna getPengguna() {
          return pengguna;
     }

     public void setPengguna(Pengguna pengguna) {
          this.pengguna = pengguna;
     }
    
        
}
    
